package chances.epg.navigator.template.loader;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;

import chances.epg.commons.log.EpgLogFactory;
import chances.epg.data.service.BizService;
import chances.epg.entity.biz.TemplateBind;
import chances.epg.entity.biz.TemplateParamInst;
import chances.epg.navigator.template.TemplateConfig;
import chances.epg.navigator.template.TemplateParameter;

public class DBTemplateConfigLoader implements TemplateConfigLoader {
	private static Logger logger = EpgLogFactory.getSystemLogger();

	
	private BizService bizService;

	public DBTemplateConfigLoader(BizService bizService){
		this.bizService = bizService;
	}


	public Collection<TemplateConfig> loadTemplateConfig() {
		logger.debug("Begin load template bind.");
		List<TemplateBind> templateBinds = this.bizService.getAllTemplateBind();

		TemplateConfig tmpConfig = null;
		Map<Long, TemplateConfig> templateConfigs = new HashMap<Long, TemplateConfig>();
		for (TemplateBind templateBind : templateBinds) {
			tmpConfig = new TemplateConfig();
			tmpConfig.setBizCode(templateBind.getBizCode());
			tmpConfig.setContentType(templateBind.getContentType());
			tmpConfig.setTemplatePackageCode(templateBind.getTemplatePackageCode());
			tmpConfig.setTemplatePath(templateBind.getTemplatePath());
			tmpConfig.setTemplateType(templateBind.getTemplateType());

			templateConfigs.put(templateBind.getId(), tmpConfig);
		}

		List<TemplateParamInst> allParamInsts = this.bizService.getAllTemplateParameter();
		for (TemplateParamInst paramInst : allParamInsts) {
			tmpConfig = templateConfigs.get(paramInst.getTemplateBindId());
			if (tmpConfig != null) {
				tmpConfig.getTemplateParams().add(this.createTemplateParameter(paramInst));
				templateConfigs.put(paramInst.getTemplateBindId(), tmpConfig);
			}
		}
		logger.debug("End load template bind.");
		// 初始化
		return templateConfigs.values();



	}

	private TemplateParameter createTemplateParameter(TemplateParamInst paramInst) {
		TemplateParameter ret = new TemplateParameter();

		ret.setName(paramInst.getParamName());
		ret.setType(paramInst.getParamType());
		ret.setValue(paramInst.getParamValue());

		return ret;
	}

	public BizService getBizService() {
		return bizService;
	}

	public void setBizService(BizService bizService) {
		this.bizService = bizService;
	}
}
